#!/usr/bin/env bash

# Copyright 2018 The Fuchsia Authors
#
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT

readonly SCRIPT_DIR="$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)"
readonly ZIRCON_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
readonly PREBUILTS_DIR="$(cd "${ZIRCON_ROOT}/prebuilt" && pwd)"
readonly DOWNLOAD_DIR="${PREBUILTS_DIR}/downloads"

set -o pipefail

cipd_ok=true
case "$#:$1" in
0:)
  mode=update
  ;;
1:--resolve)
  mode=resolve
  ;;
*)
  echo >&2 "Usage: $0 [--resolve]"
  exit 1
  ;;
esac
readonly cipd_ok

case "$(uname)-$(uname -m)" in
Darwin-x86_64)
  PLATFORM=mac-amd64
  ;;
Linux-x86_64)
  PLATFORM=linux-amd64
  ;;
Linux-aarch64)
  PLATFORM=linux-arm64
  ;;
*)
  echo 'Unknown operating system.'
  exit 1
  ;;
esac
readonly PLATFORM

find_cipd() {
  # If the Zircon checkout is part of a jiri checkout that includes
  # //buildtools, then find cipd there.  Otherwise, if cipd is in
  # the PATH, take it from there.
  type -p "${ZIRCON_ROOT}/../.jiri_root/bin/cipd" || type -p cipd
}

run_cipd() {
  "$@" \
    -ensure-file "${PREBUILTS_DIR}/zircon_internal.ensure" \
    -log-level warning
}

write_config() {
  local -r internal_access="$1"
  local -r config_gni="${PREBUILTS_DIR}/config.gni"
  rm -f -- "$config_gni"
  echo > "$config_gni" "# Generated by $0.  DO NOT EDIT!
have_firmware = $internal_access"
}

update() {
  local CIPD
  local internal_access=false
  if $cipd_ok && CIPD="$(find_cipd)"; then
    # We have CIPD, so use it.
    if [[ "$("$CIPD" ls fuchsia_internal | tail -1)" != "No matching packages." ]]; then
      internal_access=true
      run_cipd "$CIPD" ensure -root "$DOWNLOAD_DIR" || return
    fi
  fi
  write_config "$internal_access"
}

resolve() {
  run_cipd "$(find_cipd)" ensure-file-resolve
}

$mode
